package com.xinziruo.crawl.interfaces.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xinziruo.crawl.application.crawl.CrawlApiObjectScheduleService;
import com.xinziruo.crawl.application.crawl.CrawlApiObjectService;
import com.xinziruo.crawl.domain.crawl.CrawlApiObject;
import com.xinziruo.crawl.domain.crawl.CrawlApiObjectFactory;
import com.xinziruo.crawl.domain.crawl.api.Channel;
import com.xinziruo.crawl.infrastruture.persist.hibernate.impl.ChannelRepositoryImpl;
import com.xinziruo.crawl.infrastruture.persist.hibernate.query.HQLQuery;
import com.xinziruo.crawl.infrastruture.util.Page;
import com.xinziruo.crawl.interfaces.controller.support.ControllerSupport;
import com.xinziruo.crawl.infrastruture.util.EntityUtils;

/**
 * 
 * @author loudyn
 * 
 */
@Controller
@RequestMapping("/crawl-api-object")
public class CrawlApiObjectController extends ControllerSupport {

	public static final String REDIRECT_LIST = "redirect:/crawl-api-object/list";
	
	

	/**
	 * 
	 * @param page
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Page<CrawlApiObject> page, HttpServletRequest request, Model model) {

		HQLQuery query = new HQLQuery().table("CrawlApiObject")
										.like("name", request.getParameter("name"));

		page = CrawlApiObjectService.queryPage(page, query.hql(), query.values());
		model.addAttribute(page);
		return "crawl-api-object/list";
	}

	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(HttpServletRequest request,Model model) {
		String templateString=request.getParameter("template");
		Integer templateInt=0;
		if(!"".equals(templateString)&&templateString!=null){
			templateInt=Integer.parseInt(templateString);
		}
		String template_str;
		File file = new File(this.getClass().getResource("/META-INF/template").getPath());
        String[] files=file.list();
        Map<Integer, String> templates = new HashMap<Integer, String>();
        Integer index=0;
        for(String f:files){
        	index++;
        	templates.put(index,"/META-INF/template/"+f);
        }
        model.addAttribute("templates",templates);
        if (templateInt == 0 || null == templateInt) {
        	template_str = "/META-INF/template/empty.json";
		}else {
			template_str=templates.get(templateInt);
		}

        model.addAttribute("templateInt",templateInt);
		model.addAttribute(CrawlApiObjectFactory.create(template_str));
		return "crawl-api-object/form";
	}

	/**
	 * 
	 * @param entity
	 * @param result
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(CrawlApiObject entity, BindingResult result) {
		if (result.hasErrors()) {
			return null;
		}
		crawlScheduleService.registerCrawlJob(entity.verifyParseExpressions());
		return REDIRECT_LIST;

	}

	/**
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}/getchild", method = RequestMethod.GET)
	@ResponseBody
	public List<Channel>  getchild(@PathVariable("id") String id, Model model) {
		 //System.out.println("id----------"+id);
		 String hql ="from Channel where  father_id=? ";
	     List<Channel> channelList=channelRepositoryImpl.query(hql,id);
		return channelList;
	}
	
	
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	public String edit(@PathVariable("id") String id, Model model) {		
		CrawlApiObject crawlApiObject =CrawlApiObjectService.get(id);
		model.addAttribute("_method", "put").addAttribute(crawlApiObject);
		
		return "crawl-api-object/form";
	}

	/**
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.PUT)
	public String edit(@PathVariable("id") String id, HttpServletRequest request) {

		try {

			CrawlApiObject entity = CrawlApiObjectService.get(id);
			bind(request, entity);

			crawlScheduleService.registerCrawlJob(entity.verifyParseExpressions());
			return REDIRECT_LIST;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") String id) {

		CrawlApiObject entity = CrawlApiObjectService.get(id);
		crawlScheduleService.removeCrawlJob(entity);

		return REDIRECT_LIST;
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	public String delete(HttpServletRequest request) {

		String[] items = EntityUtils.nullSafe(request.getParameterValues("items"), new String[] {});
		for (String item : items) {
			delete(item);
		}

		return REDIRECT_LIST;
	}

	@Autowired
	private ChannelRepositoryImpl channelRepositoryImpl;
	
	@Autowired
	private CrawlApiObjectService CrawlApiObjectService;

	@Autowired
	private CrawlApiObjectScheduleService crawlScheduleService;
}
